package com.me.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.me.entity.ChoiceLib;
import com.me.entity.StudentPaper;
import com.me.service.ChoiceLibService;
import com.me.service.ConfigService;
import com.me.service.StudentPaperService;
import com.me.util.EasyUIFormat;
import com.me.util.RandomUtil;

@Controller
@RequestMapping("/choiceLib")
@SessionAttributes("choices")	// 试卷所有选择题
public class ChoiceLibController extends BaseController {
	/**
	 * 注入业务组件
	 */
	@Resource
	private ChoiceLibService choiceLibService;
	@Resource
	private StudentPaperService studentPaperService;
	@Resource
	private ConfigService configService;

	/**
	 * 跳转到choiceLib主页
	 */
	@RequestMapping("/index.do")
	public String toMember(){
		return "admin/main/choice_lib";
	}
	
	/**
	 * 查询选择题题库
	 */
	@RequestMapping("/queryPage.do")
	@ResponseBody
	public Map<String, Object> queryAll(){
		List<ChoiceLib> libs = choiceLibService.queryAll();
		return EasyUIFormat.formatEntities(libs);
	}
	
	/**
	 * 新增选择题
	 */
	@RequestMapping("/insert.do")
	@ResponseBody
	public Map<String, Object> insert(ChoiceLib choiceLib){
		try {
			LOG.info("--------插入记录：" + choiceLib + "--------");
			choiceLibService.insert(choiceLib);
			return messageSuccess();
		} catch (Exception e) {
			return messageFailure(e.getMessage(), "插入记录失败！");
		}
	}
	
	/**
	 * 修改选择题
	 * 
	 */
	@RequestMapping("/update.do")
	@ResponseBody
	public Map<String, Object> update(ChoiceLib choiceLib){
		try {
			LOG.info("--------修改记录：" + choiceLib + "--------");
			choiceLibService.update(choiceLib);
			return messageSuccess();
		} catch (Exception e) {
			return messageFailure(e.getMessage(), "修改记录失败！");
		}
	}
	
	/**
	 * 转到选择题列表
	 */
	@RequestMapping("/choiceList.do")
	public String listChoice(Model model, HttpSession session){
		// 获取session中的学生记录
		StudentPaper studentPaper = (StudentPaper) session.getAttribute("student");
		LOG.info("-------------Session中的试卷信息：" + studentPaper + "-------------");
		// 判断试卷的状态，若试卷状态为1-已经开考, 则不再从题库拉题, 若状态为 3-已经提交试卷，则退出登录
/*		Integer paperStatus = studentPaperService.getPaperStatus(studentPaper);
		LOG.info("-------------当前试卷状态：" + paperStatus + "-------------");
		if(paperStatus == 3){
			return "redirect:/login/toLogin.do";
		}*/
		// 如果session中已经存在选择题，则不再从题库拉取
		if(session.getAttribute("choices") != null){
			return "student/main/choice_list";
		}
		// 开始拉取题库中的选择题
		try {
			// 获取整个题库的选择题
			List<ChoiceLib> choicesAll = choiceLibService.queryAll();
			// 题库中的总选择题数量
			int totalSize = choicesAll.size();
			// 系统设置好的选择题个数
			int configSize = configService.getChoiceNum();
			// 封装最终的选择题
			List<ChoiceLib> choices = new ArrayList<>();
			if(totalSize >= configSize){
				// 生成随机下标
				int[] nums = RandomUtil.genRandomNums(totalSize, configSize);
				// 随机筛选选择题
				for(int index : nums){
					choices.add(choicesAll.get(index));
				}
			} else{
				choices.addAll(choicesAll);
			}
			
			// 将这些选择题的信息更新到学生试卷表中
			// 1.选择题的题号序列串，以,隔开
			// 2.选择题的正确答案序列串，以,隔开
			StringBuilder choiceIds = new StringBuilder();
			StringBuilder choiceAnswers = new StringBuilder();
			for (int i = 0; i < configSize; i++) {
				if (i < configSize - 1) {
					choiceIds.append(choices.get(i).getId()).append(",");
					choiceAnswers.append(choices.get(i).getChoiceAnswer()).append(",");
				} else {
					choiceIds.append(choices.get(i).getId());
					choiceAnswers.append(choices.get(i).getChoiceAnswer());
				}
			}
			// 执行更新操作，同时也会更新session中的信息
			studentPaper.setChoiceId(choiceIds.toString());
			studentPaper.setChoiceAccurateAnswer(choiceAnswers.toString());
			LOG.info("-------------更新试卷信息：" + studentPaper + "-------------");
			studentPaperService.updateByAccount(studentPaper);
			// 将试题转发到JSP页面
			model.addAttribute("choices", choices);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "student/main/choice_list";
	}
}
